﻿package com.petermacko.utils {
	import flash.display.*;
	import flash.events.*;
	import flash.text.*;
	
	public class Debugger extends MovieClip
	{
		public var ACTIVE:Boolean = false;
		
		public var b:SimpleButton;
		public var f:TextField;
		public var bg:Sprite;

		private var w:int,h:int; //stageWidth,stageHeight
		private var s:int = 14; //size
		
		private var l:Array = new Array(); //log data
		
		public function Debugger(stg:Stage) {
			arrange(stg.stageWidth,stg.stageHeight);
			stg.addEventListener(Event.RESIZE, onStageResize);
			makeField();
			makeButton();
		}
		public function log(str:String):void {
			l.push(str);
			f.appendText(str+"\n");
			ACTIVE = f.visible = bg.visible = true;
		}

		private function arrange(we:int,he:int):void {
			w = we;
			h = he;
			x = y = 0;
		}
		private function makeField():void {
			var ff:TextFormat = new TextFormat();
				ff.color = 0xEEEEEE;
				ff.size = 10;
				ff.font = "Verdana";
				ff.leftMargin = ff.rightMargin = 2;
				ff.leading = 4;
			var bs:Shape = new Shape();
				bs.graphics.beginFill(0x333333,0.65);
				bs.graphics.drawRect(1+s,1+s,224,344);
				bs.graphics.endFill();
			bg = new Sprite();
			bg.addChild(bs);
			addChild(bg);
			f = new TextField();
			f.type = TextFieldType.DYNAMIC;
			f.border = f.multiline = f.wordWrap = f.mouseWheelEnabled = true;
			f.borderColor = 0x444444;
			f.width = 227;
			f.height = 347;
			f.x = f.y = s-1;
			f.defaultTextFormat = ff;
			addChild(f);
			f.visible = bg.visible = false;
		}
		private function makeButton():void {
			if(b) {
				removeChild(b);
			}
			b = new SimpleButton();
			b.overState = b.downState = butShape(0x000000, s);
			b.upState = b.hitTestState = butShape(0x333333, s);
			b.addEventListener(MouseEvent.CLICK, onButtonClick);
			addChild(b);
		}
		private function butShape(bc:uint,sz:uint):Shape {
			var h:Shape = new Shape();
				h.graphics.beginFill(bc,0.4);
				h.graphics.drawRect(1,1,sz-2,sz-2);
				h.graphics.endFill();
			return h;
		}
		private function onButtonClick(e:MouseEvent):void {
			ACTIVE = (ACTIVE)?false:true;
			f.visible = bg.visible = ACTIVE;
		}
		private function onStageResize(e:Event):void {
			arrange(e.target.stageWidth,e.target.stageHeight);
		}
	}
}